﻿// -----------------------------------------------------------------------
// <copyright file="SaveScreen.cs" company="Diddly Squad">
// </copyright>
// -----------------------------------------------------------------------
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;

namespace DiddlySquat
{
	/// <summary>
	/// Screen that handles saving of the games through menu
	/// </summary>
	public class SaveScreen : Screen
	{
		//Background texture for the screen
		readonly Texture2D titleScreenBackground;

		private readonly SpriteFont font;

		private readonly List<FileMenuItem> FileMenuItems;

		private readonly GraphicsDeviceManager graphicsDeviceManager;

		private int drawPositionY;

		public FileMenuItem SelectedMenuItem { get; private set; }

		public string StatusMessage { get; set; }

		private int menuIndexer;

		private readonly ContentManager content;

		/// <summary>
		/// Initializes a new instance of the <see cref="SaveScreen"/> class.
		/// </summary>
		/// <param name="theContent">The content.</param>
		/// <param name="theScreenEvent">The screen event.</param>
		/// <param name="graphics">The graphics.</param>
		public SaveScreen(ContentManager theContent, EventHandler theScreenEvent, GraphicsDeviceManager graphics)
			: base(theScreenEvent)
		{
			this.content = theContent;
			//Load the background texture for the screen
			titleScreenBackground = content.Load<Texture2D>("GameScreen");
			font = content.Load<SpriteFont>("fonts/menufont");
			this.graphicsDeviceManager = graphics;
			drawPositionY = 150;
			this.menuIndexer = 0;
			this.FileMenuItems = new List<FileMenuItem>();
			this.CreateMenu();

		}

		/// <summary>
		/// Updates the screen.
		/// </summary>
		/// <param name="theTime">The time.</param>
		public override void Update(GameTime theTime)
		{

			state = Keyboard.GetState();
			//Move up on the menu - check if goes around
			if (CheckKey(Keys.Up))
			{
				FileMenuItems[this.menuIndexer].IsSelected = false;
				if (this.menuIndexer == 0)
					this.menuIndexer = FileMenuItems.Count - 1;
				else
					this.menuIndexer--;

				this.SelectedMenuItem = FileMenuItems[this.menuIndexer];
				this.SelectedMenuItem.IsSelected = true;
			}
			//Move down on the menu - check if goes around
			if (CheckKey(Keys.Down))
			{
				FileMenuItems[this.menuIndexer].IsSelected = false;
				if (this.menuIndexer == FileMenuItems.Count - 1)
					this.menuIndexer = 0;
				else
					this.menuIndexer++;

				this.SelectedMenuItem = FileMenuItems[this.menuIndexer];
				this.SelectedMenuItem.IsSelected = true;

			}
			else if (CheckKey(Keys.Enter) || CheckKey(Keys.Space))
			{
					ScreenEvent.Invoke(this, new EventArgs());
			}


			base.Update(theTime);
			oldState = Keyboard.GetState();
		}

		/// <summary>
		/// Refreshes the menu.
		/// </summary>
		public void RefreshMenu()
		{
			this.FileMenuItems.Clear();
			this.CreateMenu();
			this.StatusMessage = string.Empty;
			this.menuIndexer = 0;
		}

		/// <summary>
		/// Draws to the batch.
		/// </summary>
		/// <param name="theBatch">The batch.</param>
		public override void Draw(SpriteBatch theBatch)
		{
			
			theBatch.Draw(titleScreenBackground, Vector2.Zero, Color.White);

			drawPositionY = 65;

			if (!string.IsNullOrEmpty(StatusMessage))
				theBatch.DrawString(font, StatusMessage, new Vector2(graphicsDeviceManager.GraphicsDevice.Viewport.Width / 2 - (int)font.MeasureString(StatusMessage).X, this.drawPositionY), Constants.StatusSuccessfullColor);

			drawPositionY = 100;

			foreach (FileMenuItem fileMenuItem in FileMenuItems)
			{
				Color itemColor = fileMenuItem.IsSelected ? Constants.SelectedMenuItemColor : Constants.MenuItemColor;
				this.drawPositionY += font.LineSpacing;

				//Display file info
				string text = fileMenuItem.Text;
				if (fileMenuItem.MenuItemType == Enums.MenuItemType.File)
					text = fileMenuItem.Text + " (" + fileMenuItem.CreationDate + ")";

				theBatch.DrawString(font, text, new Vector2(graphicsDeviceManager.GraphicsDevice.Viewport.Width / 2 - (int)font.MeasureString(fileMenuItem.Text).X, this.drawPositionY), itemColor);
			}

			
			base.Draw(theBatch);
		}

		/// <summary>
		/// Creates the menu.
		/// </summary>
		private void CreateMenu()
		{
			FileMenuItems.Add(new FileMenuItem(Constants.NewSave, Enums.MenuItemType.NewSave));

			//Get *.sav files from the XNA storage
			IAsyncResult res = StorageDevice.BeginShowSelector(null, null);
			if (res.IsCompleted)
			{

				StorageDevice device = StorageDevice.EndShowSelector(res);
				// Open a storage container.
				IAsyncResult result = device.BeginOpenContainer("DiddlySquat", null, null);

				// Wait for the WaitHandle to become signaled.
				result.AsyncWaitHandle.WaitOne();

				StorageContainer container = device.EndOpenContainer(result);

				// Close the wait handle.
				result.AsyncWaitHandle.Close();

				foreach (string fileName in container.GetFileNames("*.sav"))
				{
					//Do not overwrite quicksave
					if (fileName != Constants.QuickSave)
					{
						var fileMenuItem = FileMenuItem.CreateFileMenuItem(fileName);
						FileMenuItems.Add(fileMenuItem);
					}
				}

				// Dispose the container.
				container.Dispose();
			}
			FileMenuItems.Add(new FileMenuItem(Constants.MenuOptionBack, Enums.MenuItemType.Back));
			FileMenuItems[0].IsSelected = true;
			this.SelectedMenuItem = FileMenuItems[0];
		}
	}
}
